/*
 * Created on 15/11/2009
 *
 * To change the template for this generated file go to
 * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments
 */
package org.jma.lib.utils.http;


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;

import org.dangoldberg.app.http.Plugin;
import org.jma.lib.soap.HttpRequest;
import org.jma.lib.soap.HttpResponse;
import org.jma.lib.soap.events.SOAPSessionEvent;
import org.jma.lib.soap.exceptions.HttpException;
import org.jma.lib.soap.sessions.SOAPSession;
import org.jma.lib.soap.sessions.SOAPSessionException;
import org.jma.lib.soap.sessions.SOAPSessionFilter;
import org.jma.lib.soap.sessions.SOAPSessionListener;

public class FileUploader implements Plugin{
	String name;
	String fileName;
	int uploadedBytes=0;
	String repository="";
	private ArrayList  FileUploadedListeners=new ArrayList();
	
	
	/**
	 * @return the name
	 */
	public String getAuxField() {
		return name;
	}

	/**
	 * @param name the name to set
	 */
	public void setAuxField(String name) {
		this.name = name;
	}
	
	/**
	 * @return the name
	 */
	public String getFileName() {
		return fileName;
	}

	/**
	 * @param name the name to set
	 */
	public void setFileName(String filename) {
		this.fileName = fileName;
	}
	
	/**
	 * @return the repository
	 */
	public  String getRepository() {
		return repository;
	}

	/**
	 * @param repository the repository to set
	 */
	public  void setRepository(String rep) {
		repository = rep;
	}

	private String readLine(InputStream is) throws IOException{
		char a='\n';
		StringBuffer sb =new StringBuffer();
		//if (is.available()>0){ 
		//we can't check availability because SSLsocket always returns 0
		try{
			a = (char) is.read();

			while (a=='\n') a = (char) is.read();
			while (a != '\n'){
				if (a!='\r') sb.append(a);
				a = (char) is.read();
			}
		} catch(Exception e){ e.printStackTrace();}

		return sb.toString();
	}
	
	public String doGet(
			HttpRequest request, HttpResponse response)
			throws HttpException, IOException {
		  return doPost(request, response);
	}

	public String doPost(
			HttpRequest request, HttpResponse response)
	throws HttpException, IOException {
		InputStream dis =  request.getInputStream();
		String line,fileName="",mark="";
		//no!! http header
		
		line=readLine(dis);
		while (!line.equals("")){
			line=readLine(dis);
		}
		
		line=readLine(dis);
		while (!line.equals("")){		
			if (line.startsWith("---")) mark += line; 
			else if (line.indexOf("filename")>0)
				fileName= line.substring(line.indexOf("filename")+10,line.lastIndexOf('"'));
			else if (line.equals("")) break;
			line=readLine(dis);
		}
		fileName=cleanFileName(fileName);
		
		
		
		File dir=new File(repository);
		if (!dir.exists()) dir.mkdirs();		
		File f=new File(repository+fileName);
		f.createNewFile();
		FileOutputStream fos = new FileOutputStream(f);


		byte[] buffer= new byte[4096];
		int len=0;
		uploadedBytes=0;
		byte[] bmark = mark.getBytes();


		
		while((len=dis.read(buffer))>-1) {
			len=checkBuffer(buffer,bmark,len);	
			fos.write(buffer,0,len);
			if (bmark[0]==-127)break;
			uploadedBytes+=len;
		}


		System.out.println("Ok");
		fos.flush();
		fos.close();	
		dis.close();
		fireFileUploadedListener(fileName);
		return fileName;
	}	
	
	private String cleanFileName(String fileName) {
		if (fileName.contains("/"))
			return fileName.substring(fileName.lastIndexOf("/")+1);
		if (fileName.contains("\\"))
			return fileName.substring(fileName.lastIndexOf("\\")+1);
		return fileName;
	}

	private int checkBuffer(byte[] buffer, byte[] bmark,int length) {
		int i=0,j=0,n=0;
		int bmarkLength=bmark.length-1;
		for (i=0;i<length;i++){
			j=0;
			n=i;
			while ((buffer[n]==bmark[j])&& (n<length-1) &&(j<bmarkLength)) {j++;n++;}
			
			if (j==bmarkLength) {
				bmark[0]=-127; //dummy mark
				return i;
			}
				
		}
		return length;
	}

	int getUploadedBytes(HashMap params){
		return uploadedBytes;
	}
	
	
	private void fireFileUploadedListener(String file){

		if (!FileUploadedListeners.isEmpty()) {
			for (int i = 0; i < FileUploadedListeners.size(); i++) {
				FileUploadedListener ful =
					(FileUploadedListener) FileUploadedListeners.get(i);
				ful.fileUploaded(new FileUploadedEvent(file,this));
			}
		}

	}


	public  void addFileUploadedListener(FileUploadedListener ful) {
		FileUploadedListeners.add(ful);

	}

	public  void removeFileUploadedListener(FileUploadedListener ful) {
		FileUploadedListeners.remove(ful);
	}
}
